package com.ebt.m.utils;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.provider.MediaStore;
import android.util.Log;

import com.ebt.m.commons.buscomponent.permission.RxPermissions;
import com.ebt.m.commons.widgets.BaseRxActivity;

import java.io.File;


/**
 * 图片获取帮助类
 *
 * @author Michael.li
 */
public class PhotoCaptureUtil implements OnActivityResultListener {
    /**
     * 相册获取取
     */
    public static final int FROM_ALBUM = 0;
    /**
     * 拍照获取
     */
    public static final int FROM_CAMERA = 1;

    private static final String IMAGE_UNSPECIFIED = "image/*";
    /**
     * 拍照
     */
    private static final int REQUESTCODE_CAMERA = 1001;
    /**
     * 剪裁
     */
    private static final int REQUESTCODE_CROP = 1002;
    /**
     * 处理结果
     */
    private static final int REQUESTCODE_RESULT = 1003;

    private Context mContext;
    private int mWidth, mHeight;// 宽度和高度
    private String mPath;// 存放路径
    private boolean mFromPortrait = false;//是否头像裁剪

    /**
     * @param context
     */
    public PhotoCaptureUtil(Context context) {
        mContext = context;
    }

    public void setFrom(boolean fromPortrait) {
        this.mFromPortrait = fromPortrait;
    }

    /**
     * @param from   从相册/拍照
     * @param width  图片宽度
     * @param height 图片高度
     * @param path   图片完整路径名 包括文件名
     */
    public void startActivity(int from, int width, int height, String path) {
        mWidth = width;
        mHeight = height;
        mPath = path;
        BaseRxActivity activity = (BaseRxActivity) mContext;
        if (activity == null) {
            System.err.println("PhotoCaptureUtil error");
            return;
        }
        activity.setOnActivityResultListener(this);
        if (from == FROM_ALBUM) {
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
            activity.startActivityForResult(intent, REQUESTCODE_CROP);
        } else {

            RxPermissions rxPermissions = new RxPermissions(activity);
            rxPermissions.request(Manifest.permission.CAMERA)
                    .subscribe(granted -> {
                        if (granted) {
                            try {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                Uri tempUri = getTempPictureURI();
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                                if (Build.VERSION.SDK_INT >= 24) {
                                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    UriUtils.grantUriPermisson(intent, mContext, tempUri);
                                }
                                activity.startActivityForResult(intent, REQUESTCODE_CAMERA);
                            } catch (ActivityNotFoundException e) {
                                e.printStackTrace();
                                UIHelper.makeToast(mContext, "未安装相机程序，无法启动", true);
                            } catch (Exception e) {
                                e.printStackTrace();
                                UIHelper.makeToast(mContext, "启动相机失败", true);
                            }
                        } else {
                            com.ebt.m.commons.utils.ToastUtil.show(activity, "请允许相关权限，才能调用相机");
                        }
                    });


        }
    }

    @Override
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("525", "onActivityResult");//intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        if (requestCode == REQUESTCODE_CAMERA) {
            Log.d("525", "onActivityResult  requestCode == REQUESTCODE_CAMERA");
            if (resultCode == 0) {
                return true;
            }
            startPhotoZoom(getTempPictureURI());
            return true;
        }
        if (data == null) {
            return false;
        }
        if (requestCode == REQUESTCODE_CROP) {
            Log.d("525", "onActivityResult  requestCode == REQUESTCODE_CROP");
            startPhotoZoom(data.getData());
            return true;
        }
        if (requestCode == REQUESTCODE_RESULT) {
            Log.d("525", "onActivityResult  requestCode == REQUESTCODE_RESULT");
            Bitmap photo = null;
            Uri imageUri = data.getData();
            if (imageUri == null) {
                imageUri = getFilePortraitUri();
            }
            if (imageUri == null) {
                return false;
            }

            if (mListener != null) {
                mListener.onPhotoCaptured(UriUtils.getPathFromUri(mContext, imageUri));
            }
            return true;
        }
        return false;
    }

    /**
     * 调用系统activity进行图片缩放
     *
     * @param uri -
     */
    private void startPhotoZoom(Uri uri) {
        Uri outUri = getTempPortraitUri();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        if (mFromPortrait) {
            // aspectX aspectY 是宽高的比例(截取图片的虚线框的比例)
            intent.putExtra("aspectX", mWidth);
            intent.putExtra("aspectY", mHeight);
        }
        // outputX outputY 是裁剪图片宽高(输出图片的宽高)
        intent.putExtra("outputX", mWidth);
        intent.putExtra("outputY", mHeight);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
        if (Build.VERSION.SDK_INT >= 24) {
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            UriUtils.grantUriPermisson(intent, mContext, outUri);
        }
        ((BaseRxActivity) mContext).startActivityForResult(intent, REQUESTCODE_RESULT);
    }

    private Uri getTempPictureURI() {
        File file = new File(ConfigData.DATA_PATH, "temp.jpg");
        return UriUtils.getUriFromFile(file);
    }

    private Uri getTempPortraitUri() {
        File file = new File(ConfigData.PORTRAITPATH, "temp.jpg");
        return UriUtils.getUriFromFile(file);
    }

    private Uri getFilePortraitUri() {
        return Uri.fromFile(new File(ConfigData.PORTRAITPATH, "temp.jpg"));
    }

    public interface OnPhotoCaptureListener {
        /**
         * 文件路径
         *
         * @param path
         */
        void onPhotoCaptured(String path);
    }

    private OnPhotoCaptureListener mListener;

    public void setOnPhotoCaptureListener(OnPhotoCaptureListener l) {
        this.mListener = l;
    }

}
